package com.kizuki.controller;

import com.kizuki.config.DelayedQueueConfig;
import com.kizuki.config.TtlQueueConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;


/**
 * 两种延时队列
 * @see TtlQueueConfig
 * @see DelayedQueueConfig
 */
@Slf4j
@RequestMapping("ttl")
@RestController
@Api(tags = "延时队列",description = "延时队列测试")
public class SendMsgController {

    @Resource(name = "ttlRabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    // region 普通延时队列
    /**
     * 发送消息到延迟队列
     * @param message 消息的内容
     */
    @ApiOperation("队列ttl属性实现的延时队列")
    @GetMapping("sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        log.info("当前时间：{},发送一条信息给两个 TTL 队列:{}", new Date(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自 ttl 为 10S 的队列: " + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自 ttl 为 40S 的队列: " + message);
    }

    /**
     * 发送自定义延迟时间的消息到延迟队列
     * @param message 消息的内容
     * @param ttlTime ttl的时间，单位是ms
     */
    @ApiOperation("消息ttl属性实现的延时队列")
    @GetMapping("sendMsg1/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @ApiParam(name="ttlTime",value="延时时间ms") @PathVariable String ttlTime) {
        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
        log.info("当前时间：{},发送一条ttl为{}的信息给QC队列:{}", new Date(), ttlTime, message);
    }
    // endregion

    // region 插件延时队列
    /**
     * 插件的延时队列
     * @param message 消息的内容
     * @param delayTime 延迟的时间
     */
    @ApiOperation("插件实现的延时队列")
    @GetMapping("sendMsg2/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message, @ApiParam(name="delayTime",value="延时时间ms") @PathVariable Integer delayTime) {
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message, msg -> {
            msg.getMessageProperties().setDelay(delayTime);
            return msg;
        });
        log.info("当前时间：{},发送一条ttl为{}的信息给QC队列:{}", new Date(), delayTime, message);
    }
    // endregion
}